<?php
namespace api\user\controller;

use think\Db;
use think\Validate;
use fast\Random;
use api\common\controller\RestBaseController;
use api\user\model\UserModel;
use think\cache\driver\Redis;
use think\request;

class PublicController extends RestBaseController
{
    // 用户注册
    public function register()
    {
        $data   = $this->request->param();
        $result = $this->validate($data, 'Register');
        if ($result !== true) {
            $this->error($result);
        }
        $user = [];

        $findUserWhere = [];

        if (cmf_check_mobile($data['mobile'])) {
            $user['username']        = $data['mobile'];
            $findUserWhere['mobile'] = $data['mobile'];
        } else {
            $this->error("请输入正确的手机");
        }

        $errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }

        $findUserCount = Db::name("user")->where($findUserWhere)->count();

        if ($findUserCount > 0) {
            $this->error("此账号已存在!");
        }
        $findInvitedUser = [];
        if($data['invite_code']){
           $findInvitedUserWhere['invite_code'] = $data['invite_code'];

            $findInvitedUser = Db::name("user")
            ->alias('u')
            ->join('invite i','u.id=i.user_id','LEFT')
            ->where($findInvitedUserWhere)
            ->field('u.id,i.path')
            ->find();
            if (!$findInvitedUser) {
                $this->error("推荐不人存在");
            } 
        }
        

        $ip = request()->ip();
        $time = time();
        $user['nickname'] = '矿工'.$data['mobile'];
        $user['mobile']   = $data['mobile'];
        $user['jointime'] = $time;
        $user['logintime'] = $time;
        $user['prevtime'] = $time;
        $user['loginip'] = $ip;
        $user['salt'] = Random::alnum();
        $user['status'] = 'normal';
        $user['group_id']   = 1;
        $user['invite_code'] = Random::alnum();
        $user['password']   = getEncryptPassword($data['password'], $user['salt']);
        Db::startTrans();
        try {
            $result = Db::name("user")->insertGetId($user);
            if(!empty($findInvitedUser)){
                $invite['user_id']        = $result;
                $invite['invite_user_id'] = $findInvitedUser['id'];
                $invite['createtime']     = time();
                $invite['status']         = 1;
                $invite['path']           = $findInvitedUser['path'].','.$result;
                Db::name("invite")->insert($invite);
                Db::name("user")->where(['id'=>$findInvitedUser['id']])->setInc('total_zt_person');
            }else{
                Db::rollback(); 
                $this->error('注册失败');
            }
            // $output_value                   = getconfig('output_value');
            // if($output_value>0){
            //     //体验矿机
            //     $arithmetic_value               = getconfig('arithmetic_value');
            //     $active_price                   = getconfig('active_price');
            //     $now                            = time();
            //     $createtime                     = strtotime(date("Y-m-d",strtotime("+1 day")));//取当前时间整点+1天
            //     $user_miner['user_id']          = $result;
            //     $user_miner['status']           = 1;
            //     $user_miner['miner_id']         = 0;
            //     $user_miner['output_value']     = $output_value>0?$output_value:0;
            //     $user_miner['arithmetic_value'] = $arithmetic_value>0?$arithmetic_value:0;
            //     $user_miner['active_price']     = $active_price>0?$active_price:0;
            //     $user_miner['createtime']       = $createtime;
            //     Db::name("user_miner")->insert($user_miner);
            // }
            Db::commit();
            $this->success("注册并激活成功,请登录",['invite_code'=>$user['invite_code']]);
        } catch (\think\Exception\DbException $exception){
            Db::rollback();
            $this->error('注册失败');
        }
        
    }

    // 用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
        $validate = new Validate([
            'mobile' => 'require',
            'password' => 'require'
        ]);
        $validate->message([
            'mobile.require' => '请输入手机号',
            'password.require' => '请输入您的密码!'
        ]);
        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $findUserWhere = [];

        if (cmf_check_mobile($data['mobile'])) {
            $findUserWhere['mobile'] = $data['mobile'];
        } else {
            $findUserWhere['username'] = $data['mobile'];
        }

        $findUser = UserModel::get($findUserWhere);
        if (empty($findUser)) {
            $this->error("用户不存在!");
        } else {

            if($findUser['status'] =='hidden'){
                $this->error('账户异常');
            }

            if ($findUser['password'] != getEncryptPassword($data['password'], $findUser['salt'])) {
                $this->error("密码不正确!");
            }
        }
        Db::startTrans();
        try {
            $userTokenQuery = Db::name("user_token")
            ->where(['user_id'=>$findUser['id'],'type'=>1]);
            $findUserToken  = $userTokenQuery->find();
            $currentTime    = time();
            $expireTime     = $currentTime + 24 * 3600 * 10;//10天
            $token          = md5(uniqid()) . md5(uniqid());
            if (empty($findUserToken)) {
                $result = $userTokenQuery->insert([
                    'token'      => $token,
                    'user_id'    => $findUser['id'],
                    'type'       => 1,
                    'expiretime' => $expireTime,
                    'createtime' => $currentTime,
                ]);
            } else {
                $result = $userTokenQuery
                    ->where(['user_id'=>$findUser['id'],'type'=>1])
                    ->update([
                        'token'      => $token,
                        'expiretime' => $expireTime,
                        'createtime' => $currentTime
                    ]);
            }

        // $redis = new Redis(['password'=>'xjkj666']);
        // $handler = $redis->handler();
        // $expireTime = 24 * 3600 * 7;//7天
        // $result = $handler->setex($token, $expireTime, $findUser['id']); 
            if (empty($result)) {
                Db::rollback();
                $this->error("登录失败!");
            }
            Db::commit();
            $this->success("登录成功!", ['token' => $token, 'user' => $findUser]);
        } catch (\think\Exception\DbException $exception) {
                // 回滚事务
                Db::rollback();
                $this->error($exception->getMessage());
                //$this->error('购买失败');
            }
    }

    // 用户退出
    public function logout()
    {
        $userId = $this->getUserId();
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }

    // 用户密码重置
    public function passwordReset()
    {
        $validate = new Validate([
            'mobile'            => 'require',
            'password'          => 'require',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'mobile.require'            => '请输入手机号',
            'password.require'          => '请输入您的密码!',
            'verification_code.require' => '请输入手机验证码'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userWhere = [];
        if (cmf_check_mobile($data['mobile'])) {
            $userWhere['mobile'] = $data['mobile'];
        } else {
            $this->error("请输入正确的手机号码");
        }

        $errMsg = cmf_check_verification_code($data['mobile'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }
        $user['salt'] = Random::alnum();
        $user['password']   = getEncryptPassword($data['password'], $user['salt']);
        Db::name("user")->where($userWhere)->update($user);

        $this->success("密码重置成功,请使用新密码登录!");

    }
}
